<template>
  <div>
    <el-dialog :title="title" :visible.sync="visible" width="500px" append-to-body custom-class="import-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="企业用户" prop="cleanerUserId">
          <el-select v-model="form.cleanerUserId" placeholder="请选择" :disabled="!!form.cleanerId" filterable clearable>
            <el-option v-for="item in userList" :key="item.value"
              :label="item.value == form.cleanerUserId ? item.slabel : item.label" :value="item.value"
              :disabled="item.cleanerType == 1">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职责范围" prop="cleanerScope">
          <el-radio-group v-model="form.cleanerScope">
            <el-radio label="1">全部楼盘</el-radio>
            <el-radio label="2">指定楼盘</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="楼盘" prop="estateIds" v-if="form.cleanerScope == 2">
          <el-row>
            <el-col :span="18">
              <el-input v-model="estateNames" placeholder="" style="width: 240px" disabled />
            </el-col>
            <el-col :span="6">
              <el-button @click="selectEstate">选择</el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="工作职责">
          <div>
            验房：<el-switch v-model="form.houseInspectionState" active-value="0" inactive-value="1">
            </el-switch>
          </div>
          <div>
            打扫：<el-switch v-model="form.sweepState" active-value="0" inactive-value="1">
            </el-switch>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">保 存</el-button>
      </div>
    </el-dialog>
    <selectEstate v-model="estateVisible" :selectedList="selectedList" @success="selectEstateCb" />
  </div>
</template>

<script>
import selectEstate from './components/select-estate.vue'
import { debounce } from "@/utils";
import { addCleaner, editCleaner, userInfoCleaner } from '@/api/houseCleaning/cleaner';
export default {
  components: {
    selectEstate
  },
  props: {
    title: {
      default: "新增人员",
    },
    value: {
      default: false,
    },
    data: {
      default: undefined,
    },
  },
  data() {
    return {
      visible: false,
      estateVisible: false,
      form: {},
      rules: {
        cleanerUserId: [
          { required: true, message: '请选择企业用户', trigger: 'blur' }
        ],
        estateIds: [
          { required: true, message: '请选择楼盘', trigger: 'blur' }
        ],
      },
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 总条数
      total: 0,
      //列表
      list: [],
      //用户列表
      userList: [],
      //已选择列表
      selectedList: [],
      estateNames: ''
    };
  },
  watch: {
    value(newVal, oldVal) {
      if (newVal) {
        this.init();
      }
      this.visible = newVal; // 监测value的变化，并赋值。
    },
    visible(val) {
      this.$emit("input", val); // 此处监测visible目的为关闭弹窗时，重新更换value值，注意emit的事件一定要为input。
    },
  },
  methods: {
    init() {
      this.reset()
      this.getUserInfoCleaner()
    },
    reset() {
      this.form = {
        cleanerId: "", //保洁人员id
        cleanerUserId: "", //保洁用户id
        houseInspectionState: "0", //是否开启验房：0.开启；1.关闭
        sweepState: "0", //是否开启打扫：0.开启；1.关闭
        cleanerScope: "1", //职责范围：1.全部楼盘；2.指定楼盘
        estateIds: "" //楼盘id集合
      }
      this.resetForm("form");
      this.estateNames = ''
      this.selectedList = []

      for (const key in this.data) {
        if (Object.hasOwnProperty.call(this.data, key)) {
          this.form[key] = this.data[key];
        }

        this.estateNames = this.data.estateNames
      }

    },
    //用户列表
    getUserInfoCleaner() {
      userInfoCleaner().then(res => {
        if (res.code == 200) {
          this.userList = res.data.map(item => {
            let isSelectText = item.cleanerType == 1 ? '(已选择)' : ''
            return {
              label: item.userName + isSelectText,
              slabel: item.userName,
              value: item.userId,
              cleanerType: item.cleanerType
            }
          })
        }
      })
    },
    selectEstate() {
      this.estateVisible = true
    },
    selectEstateCb(data) {
      console.log('data', data)
      if (data.length) {
        let estateNameArr = data.map(item => item.estateName)
        let estateIdArr = data.map(item => item.estateId)
        this.selectedList = data
        this.estateNames = estateNameArr.join(',')
        let ids = estateIdArr.join(',')
        this.form.estateIds = ids
      }
    },
    submitForm: debounce(function () {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.cleanerId) {
            editCleaner(this.form).then(response => {
              if (response.code == 200) {
                this.$emit("success");
                this.$message.success(response.msg);
                this.visible = false;
              } else {
                this.$message.error(response.msg);
              }
            })
          } else {
            addCleaner(this.form).then(response => {
              if (response.code == 200) {
                this.$emit("success");
                this.$message.success(response.msg);
                this.visible = false;
              } else {
                this.$message.error(response.msg);
              }
            })
          }
        }
      })
    }, 500),
    cancel() {
      this.reset();
      this.visible = false;
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/assets/styles/dialog.scss";
</style>
